//
//  DateUtil.m
//  SIqICalendar
//
//  Created by SKiran on 17/2/24.
//  Copyright © 2017年 sjw. All rights reserved.
//

#import "DateUtil.h"
#import "JSONKit.h"
@implementation DateUtil
{
    NSString            *_formatterStr;
    NSCalendar          *_calendar;
    NSDateFormatter     *_dateFormatter;
}

#define ChineseMonths @[@"正月", @"二月", @"三月", @"四月", @"五月", @"六月", @"七月", @"八月",@"九月", @"十月", @"冬月", @"腊月"]

#define ChineseDays @[@"初一", @"初二", @"初三", @"初四", @"初五", @"初六", @"初七", @"初八", @"初九", @"初十",@"十一", @"十二", @"十三", @"十四", @"十五", @"十六", @"十七", @"十八", @"十九", @"二十", @"廿一", @"廿二", @"廿三", @"廿四", @"廿五", @"廿六", @"廿七", @"廿八", @"廿九", @"三十"]



- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    [self initialData];
    
    return self;
}

- (void)initialData {
    
    _calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    _formatterStr = @"yyyy-MM-dd";
    
    _dateFormatter = [[NSDateFormatter alloc]init];
    [_dateFormatter setDateFormat:_formatterStr];
}

static DateUtil *_dateUtil;
+ (DateUtil *)dateUtilShareIntance {
    if (_dateUtil == nil) {
        _dateUtil = [[DateUtil alloc]init];
    }
    return _dateUtil;
}

/**
 时间转换成时间字符串
 
 @param date 时间
 @return 转换完的字符串
 */
- (NSString *)dateToDateStr:(NSDate *)date {
    return [self dateToDateStr:date withFormatter:_formatterStr];
}

/**
 时间转换成时间字符串
 
 @param date 时间
 @return 转换完的字符串
 */
- (NSString *)dateToDateStr:(NSDate *)date withFormatter:(NSString *)formatterStr {
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:formatterStr];
    
    return [formatter stringFromDate:date];
}

/**
 时间字符串转换成时间
 
 @param dateStr 时间字符串
 @param formatterStr 格式
 @return nsdate
 */
- (NSDate *)dateStrToDate:(NSString *)dateStr withFormatter:(NSString *)formatterStr {
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:formatterStr];
    
    return [formatter dateFromString:dateStr];
}

/**
 根据日期获取day

 @param date date
 @return day日
 */
- (NSString *)dateToMonthDayStr:(NSDate *)date {
    return [self dateToDateStr:date withFormatter:@"d"];
}
/**
 所选日期的上一个月份

 @param date NSDate
 @return preDate
 */
- (NSDate *)preMonth:(NSDate *)date {
    int year = (int)[[self getComps:date]year];
    int month = (int)[[self getComps:date]month];
    if(month == 1){
        month = 12;
        year --;
    }else{
        month --;
    }
    return [self convertToDateWithYear:year Month:month Day:1];
}

/**
 所选日期的下一个月份
 
 @param date NSDate
 @return preDate
 */
- (NSDate *)nextMonth:(NSDate *)date {
    int year = (int)[[self getComps:date]year];
    int month = (int)[[self getComps:date]month];
    if(month == 12){
        month = 1;
        year ++;
    }else{
        month ++;
    }
    return [self convertToDateWithYear:year Month:month Day:1];
}

- (NSDate *)currentMonthFirstDay:(NSDate *)date {
    int year = (int)[[self getComps:date]year];
    int month = (int)[[self getComps:date]month];
    return [self convertToDateWithYear:year Month:month Day:1];
}
/**
 拆分日期

 @param date 日期
 @return 日期组件
 */
- (NSDateComponents *)getComps:(NSDate *)date {
   
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit |
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    return  [_calendar components:unitFlags fromDate:date];
}

/**
 根据所选日期取出年份与月份
 
 @param month 月份
 @param year 年
 @param date 日期
 */
- (void)setCurrentMonth:(NSInteger *)month
         andCurrentYear:(NSInteger *)year
               withDate:(NSDate *)date {
    *month = [[self getComps:date] month];
    *year = [[self getComps:date] year];
}

/**
 拼接成日期格式

 @param year 年
 @param month 月
 @param day 日
 @return 拼好的日期
 */
- (NSDate *)convertToDateWithYear:(int)year Month:(int)month Day:(int)day {

    NSString *strDate = [NSString stringWithFormat:@"%.4d-%.2d-%.2d",year,month,day];
    return [_dateFormatter dateFromString:strDate];
}

/**
 取日历的第一天

 @param date
 @return date
 */
- (NSDate *)getTheCalendarFirstDayWithDate:(NSDate *)date {
    
    NSDateComponents *dateComponnets = [self getComps:date];
    NSDate *tdate = [self convertToDateWithYear:(int)[dateComponnets year]
                                          Month:(int)[dateComponnets month]
                                            Day:1];
    
    CGFloat gap = ([[self getComps:tdate] weekday] - 1) * (24 * 60 * 60);

    NSTimeInterval late = [tdate timeIntervalSince1970];
    return [[NSDate alloc]initWithTimeIntervalSince1970:late-gap];
}

/**
 取所选日期当周的第一天
 
 @param date
 @return date
 */
- (NSDate *)getTheFirstDayInTheDateWeek:(NSDate *)date {
    
    NSDateComponents *dateComponnets = [self getComps:date];
    CGFloat todayWeek = [dateComponnets weekday] - 1;
    NSTimeInterval todayTimeInterval = [date timeIntervalSince1970];
    NSTimeInterval theFirstDaIntervaly = todayTimeInterval - todayWeek * 24 * 60 * 60;
    return [NSDate dateWithTimeIntervalSince1970:theFirstDaIntervaly];
}

/**
 计算两个日期的间隔天数

 @param serverDate 早些的日期
 @param endDate 晚些的日期
 @return 天数
 */
- (NSInteger)getDaysFrom:(NSDate *)serverDate To:(NSDate *)endDate {
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    [gregorian setFirstWeekday:2];
    
    //去掉时分秒信息
    NSDate *fromDate;
    NSDate *toDate;
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&fromDate interval:NULL forDate:serverDate];
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&toDate interval:NULL forDate:endDate];
    NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];
    
    return dayComponents.day;
}
#pragma mark - setter or getter
- (void)setDateFormatterStr:(NSString *)dateFormatterStr {
    self.dateFormatterStr = dateFormatterStr;
    _formatterStr = dateFormatterStr;
}

/**
 获取date当天的农历
 */
- (NSAttributedString *)chineseCalendarOfDate:(NSDate *)date {
    NSString *_day;
    BOOL isSpecial = NO;
    NSCalendar *chineseCalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
    NSDateComponents *components = [chineseCalendar components:NSCalendarUnitYear |NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
    //NSString *dayDate;
    NSCalendar *normalDate = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *Datecomponents = [normalDate components:NSCalendarUnitYear |NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
    
    if (components.day ==1 ) {
        _day = ChineseMonths[components.month -1];
        
    } else {
        _day = ChineseDays[components.day - 1];
    }
    //农历节日
    if (components.day == 1 && components.month == 1) {
        _day = [NSString stringWithFormat:@"%@",ChineseFestival[1]]; // 春节
        isSpecial = YES;
    }else if(components.month == 8 && components.day == 15){
        _day = [NSString stringWithFormat:@"%@",ChineseFestival[2]]; // 中秋
        isSpecial = YES;
    }else if(components.day == 1 && components.month == 1){
        _day = [NSString stringWithFormat:@"%@",ChineseFestival[0]]; // 除夕
        isSpecial = YES;
    }else if(components.month == 7 && components.day == 7){
        _day = [NSString stringWithFormat:@"%@",ChineseFestival[7]]; // 七夕
        isSpecial = YES;
    }else if(components.month == 5 && components.day == 5){
        _day = [NSString stringWithFormat:@"%@",ChineseFestival[8]]; // 端午
        isSpecial = YES;
    }
    //阳历节日
    if (Datecomponents.month == 6 && Datecomponents.day == 1) {       // 儿童节
        _day = [NSString stringWithFormat:@"%@",ChineseFestival[5]];
        isSpecial = YES;
    }else if(Datecomponents.month == 10 && Datecomponents.day == 1){  // 国庆节
        _day = [NSString stringWithFormat:@"%@",ChineseFestival[4]];
        isSpecial = YES;
    }else if(Datecomponents.month == 5 && Datecomponents.day == 1){   // 劳动节
        _day = [NSString stringWithFormat:@"%@",ChineseFestival[3]];
        isSpecial = YES;
    }else if(Datecomponents.month == 12 && Datecomponents.day == 25){ // 圣诞节
        _day = [NSString stringWithFormat:@"%@",ChineseFestival[6]];
        isSpecial = YES;
    }else if (Datecomponents.month == 5 && Datecomponents.day == 12){ // 护士节
        _day = [NSString stringWithFormat:@"%@",ChineseFestival[9]];
        isSpecial = YES;
    }else if (Datecomponents.year == 2018 && Datecomponents.month == 4 && Datecomponents.day == 5){
        _day = [NSString stringWithFormat:@"%@",ChineseFestival[10]];
        isSpecial = YES;
    }
    
    //除夕另外提出放在所有节日的末尾执行，除夕是在春节前一天，即把components当天时间前移一天，放在所有节日末尾，避免其他节日全部前移一天
    NSTimeInterval timeInterval_day = 60 * 60 * 24;
    NSDate *nextDay_date = [NSDate dateWithTimeInterval:timeInterval_day sinceDate:date];
    NSCalendar *localeCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |NSCalendarUnitDay;
    components = [localeCalendar components:unitFlags fromDate:nextDay_date];
    if (1 == components.month && 1 == components.day ) {
        NSAttributedString *attringStr = [[NSAttributedString alloc]initWithString:@"除夕" attributes:@{NSForegroundColorAttributeName:MainBlueColor}];
        return attringStr;
    }
    NSAttributedString *attringStr;
    if (isSpecial) {
        attringStr = [[NSAttributedString alloc]initWithString:_day attributes:@{NSForegroundColorAttributeName:MainBlueColor}];
    }else {
        attringStr = [[NSAttributedString alloc]initWithString:_day attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor]}];
    }
    
    return  attringStr;
}

/**
 将串班字符串转为串班数组
 
 @param changedStr 串班字符串
 @return 数组
 */
- (NSArray *)getChangedDataByChangestr:(NSString *)changedStr {
    if (changedStr == nil || [changedStr string_trim].length == 0) {
        return nil;
    }
    NSArray *temAry =  [changedStr objectFromJSONString];
    return temAry;
}

/**
 取所选日期的第二天日期
 
 @param date 所选日期
 @return 第二天
 */
- (NSDate *)theDayTomorrowDate:(NSDate *)date {
    NSTimeInterval timeinterval = [date timeIntervalSince1970];
    NSTimeInterval tomorrowTimeInterval = timeinterval + 60 * 60 * 24;
    
    NSDate *tomorrowDate = [NSDate dateWithTimeIntervalSince1970:tomorrowTimeInterval];
    return tomorrowDate;
}

/**
 将串班数组转为串班字符串
 */
- (NSString *)getChangedStrByChangedDatas:(NSArray *)changeds {
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:changeds
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

//- (NSDictionary *)roundModelToDic:(RoundModel *)model {
//    NSDictionary *roundDic = @{@"idvalue":@(model.idvalue),@"name":model.name,@"color":[[UtiliTools utilShareIntance] colorToNSString:model.color]};
//    return roundDic;
//}

//- (RoundModel *)dicToRoundModel:(NSDictionary *)dic {
//    RoundModel *model = [[RoundModel alloc]init];
//    model.idvalue = [dic[@"idvalue"] integerValue];
//    model.name = dic[@"name"];
//    model.color = [[UtiliTools utilShareIntance] strToColor:dic[@"color"]];
//    return model;
//}
//
//- (RoundModel *)judeThisDateIsExchanged:(NSDate *)date andExchanges:(NSArray *)ary {
//    NSString *key = [[DateUtil dateUtilShareIntance] dateToDateStr:date withFormatter:@"yyyy-MM-dd"];;
//    for (NSDictionary *dic in ary) {
//        if ([[dic allKeys] containsObject:key]) {
//            RoundModel *model = [self dicToRoundModel:[dic objectForKey:key]];
//            return model;
//        }
//    }
//
//    return nil;
//}

@end
